package com.ruoyi.web.controller.gas;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.base.domain.Customer;
import com.ruoyi.base.service.ICustomerService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.gas.domain.GasCarNum;
import com.ruoyi.gas.domain.GasDriverInfo;
import com.ruoyi.gas.domain.vo.CarDriverCustomerInfo;
import com.ruoyi.gas.service.IGasCarNumService;
import com.ruoyi.gas.service.IGasDriverInfoService;
import com.ruoyi.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.gas.domain.ExtSaleRecord;
import com.ruoyi.gas.service.IExtSaleRecordService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * Controller
 * 
 * @author morris
 * @date 2023-12-08
 */
@Api("扩展销售页面")
@RestController
@RequestMapping("/gas/extSale")
public class ExtSaleRecordController extends BaseController
{
    @Autowired
    private IExtSaleRecordService extSaleRecordService;

    @Autowired
    private IGasCarNumService gasCarNumService;

    @Autowired
    private IGasDriverInfoService gasDriverInfoService;

    @Autowired
    private ICustomerService customerService;

    @Autowired
    private ISysConfigService configService;
    /**
     * 查询列表
     */
    @ApiOperation("查询")
    @PreAuthorize("@ss.hasPermi('gas:extSale:list')")
    @GetMapping("/list")
    public TableDataInfo list(ExtSaleRecord extSaleRecord)
    {
        startPage();
        List<ExtSaleRecord> list = extSaleRecordService.selectExtSaleRecordList(extSaleRecord);
        processAlert(list);
        return getDataTable(list);
    }

    /**
     * 查询订单不分页
     */
    @ApiOperation("查询订单不分页")
    @PreAuthorize("@ss.hasPermi('gas:extSale:list')")
    @GetMapping("/listNoPage")
    public AjaxResult listNoPage(ExtSaleRecord extSaleRecord)
    {
        List<ExtSaleRecord> list = extSaleRecordService.selectExtSaleRecordList(extSaleRecord);
        processAlert(list);
        return AjaxResult.success(list);
    }

    private void processAlert(List<ExtSaleRecord> list){
       // List<ExtSaleRecord> records = new ArrayList<>();
        for (ExtSaleRecord record: list) {
           // ExtSaleRecord vo = new ExtSaleRecord();
            //vo.setExtSaleRecord(record);
            if (record.getSaleState().equals(2)){
                record.setYellowAlert(0);
                record.setRedAlert(0);
                record.setVoiceAlert(0);
                //records.add(vo);
                continue;
            }
            int alertSeconds = getAlertSecond();
            Date now = DateUtils.getNowDate();
            Date fromDate = record.getGoTime();
            if (fromDate == null){
                record.setYellowAlert(0);
                record.setRedAlert(0);
                record.setVoiceAlert(0);
                //records.add(vo);
                continue;
            }
            long diffInMillies = fromDate.getTime() - now.getTime();
            if (diffInMillies <= 0){
                //已超过当前日期
                if (record.getColorAlertProc().equals(2)) {
                    //已处理过颜色不告警
                    record.setYellowAlert(0);
                    record.setRedAlert(0);
                }
                else{
                    record.setYellowAlert(0);
                    record.setRedAlert(1);
                }
                if (record.getVoiceAlertProc().equals(2)) {
                    record.setVoiceAlert(0);
                }
                else{
                    record.setVoiceAlert(1);
                }
            }
            else{
                if (diffInMillies > alertSeconds*1000){
                    //未到黄色告警时间
                    record.setYellowAlert(0);
                    record.setRedAlert(0);
                    record.setVoiceAlert(0);
                }
                else{
                    //超过了黄色告警时间
                    if (record.getColorAlertProc().equals(2)){
                        //已处理过颜色不告警
                        record.setYellowAlert(0);
                        record.setRedAlert(0);
                    }
                    else{
                        record.setYellowAlert(1);
                        record.setRedAlert(0);
                    }
                }
            }
            //records.add(vo);
        }
        return;
    }
    private int getAlertSecond()
    {
        String alertSeconds = configService.selectConfigByKey("alertSeconds");
        if (StringUtils.isEmpty(alertSeconds)){
            alertSeconds = "900";
        }
        return Integer.parseInt(alertSeconds);
    }
    /**
     * 获取相关信息
     */
    @ApiOperation("获取基础信息")
    @PreAuthorize("@ss.hasPermi('gas:extSale:list')")
    @GetMapping("/baseinfo")
    public AjaxResult queryBaseInfo()
    {
        CarDriverCustomerInfo carDriverCustomerInfo = new CarDriverCustomerInfo();
        Customer customer = new Customer();
        customer.setCustomerType("1;2;3");
        carDriverCustomerInfo.setCustomersList(customerService.selectCustomerList(customer));
        GasDriverInfo driverInfo = new GasDriverInfo();
        carDriverCustomerInfo.setDriverInfoList(gasDriverInfoService.selectGasDriverInfoList(driverInfo));
        GasCarNum carNum = new GasCarNum();
        carDriverCustomerInfo.setCarNumsList(gasCarNumService.selectGasCarNumList(carNum));
        String alertSeconds = configService.selectConfigByKey("alertSeconds");
        if (StringUtils.isEmpty(alertSeconds)){
            alertSeconds = "900";
        }
        carDriverCustomerInfo.setAlertSeconds(Integer.parseInt(alertSeconds));
        return AjaxResult.success(carDriverCustomerInfo);
    }
    /**
     * 导出列表
     */
    @PreAuthorize("@ss.hasPermi('gas:extSale:export')")
    @Log(title = "", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ExtSaleRecord extSaleRecord)
    {
        List<ExtSaleRecord> list = extSaleRecordService.selectExtSaleRecordList(extSaleRecord);
        ExcelUtil<ExtSaleRecord> util = new ExcelUtil<ExtSaleRecord>(ExtSaleRecord.class);
        util.exportExcel(response, list, "数据");
    }

    /**
     * 获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('gas:extSale:query')")
    @GetMapping(value = "/{saleRecordId}")
    public AjaxResult getInfo(@PathVariable("saleRecordId") Long saleRecordId)
    {
        return success(extSaleRecordService.selectExtSaleRecordBySaleRecordId(saleRecordId));
    }

    /**
     * 新增
     */
    @ApiOperation("新增订单")
    @PreAuthorize("@ss.hasPermi('gas:extSale:add')")
    @Log(title = "", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ExtSaleRecord extSaleRecord)
    {
        return toAjax(extSaleRecordService.insertExtSaleRecord(extSaleRecord));
    }

    /**
     * 修改
     */
    @ApiOperation("修改订单")
    @PreAuthorize("@ss.hasPermi('gas:extSale:edit')")
    @Log(title = "", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ExtSaleRecord extSaleRecord)
    {
        return toAjax(extSaleRecordService.updateExtSaleRecord(extSaleRecord));
    }

    /**
     * 调度录入
     */
    @ApiOperation("调度录入")
    @PreAuthorize("@ss.hasPermi('gas:extSale:editDispatch')")
    @Log(title = "", businessType = BusinessType.UPDATE)
    @PostMapping("/dispatch")
    public AjaxResult editDispatch(@RequestBody ExtSaleRecord extSaleRecord)
    {
        return toAjax(extSaleRecordService.updateExtSaleRecord(extSaleRecord));
    }

    /**
     * 充装数据
     */
    @ApiOperation("充装数据")
    @PreAuthorize("@ss.hasPermi('gas:extSale:editFullfill')")
    @Log(title = "", businessType = BusinessType.UPDATE)
    @PostMapping("/fullFill")
    public AjaxResult editFullfill(@RequestBody ExtSaleRecord extSaleRecord)
    {
        return toAjax(extSaleRecordService.updateExtSaleRecord(extSaleRecord));
    }
    /**
     * 删除
     */
    @ApiOperation("删除")
    @PreAuthorize("@ss.hasPermi('gas:extSale:remove')")
    @Log(title = "", businessType = BusinessType.DELETE)
	@DeleteMapping("/{saleRecordIds}")
    public AjaxResult remove(@PathVariable Long[] saleRecordIds)
    {
        return toAjax(extSaleRecordService.deleteExtSaleRecordBySaleRecordIds(saleRecordIds));
    }

    /**
     * 订单完成
     */
    @ApiOperation("订单完成")
    @PreAuthorize("@ss.hasPermi('gas:extSale:finish')")
    @Log(title = "", businessType = BusinessType.UPDATE)
    @PostMapping("/{saleRecordId}")
    public AjaxResult orderFinish(@PathVariable Long saleRecordId)
    {
        return toAjax(extSaleRecordService.saleFinishBySaleRecordId(saleRecordId));
    }

    /**
     * 处理声音告警
     */
    @ApiOperation("处理声音告警")
    @PreAuthorize("@ss.hasPermi('gas:extSale:finish')")
    @Log(title = "", businessType = BusinessType.UPDATE)
    @PostMapping("/voiceAlert/{saleRecordId}")
    public AjaxResult voiceAlert(@PathVariable Long saleRecordId)
    {
        return toAjax(extSaleRecordService.voiceAlertBySaleRecordId(saleRecordId));
    }
    /**
     * 处理颜色告警
     */
    @ApiOperation("处理颜色告警")
    @PreAuthorize("@ss.hasPermi('gas:extSale:finish')")
    @Log(title = "", businessType = BusinessType.UPDATE)
    @PostMapping("/colorAlert/{saleRecordId}")
    public AjaxResult colorAlert(@PathVariable Long saleRecordId)
    {
        return toAjax(extSaleRecordService.colorAlertBySaleRecordId(saleRecordId));
    }
    /**
     * 查询所有未完成的订单
     */
    @ApiOperation("查询所有未完成的订单")
    @PreAuthorize("@ss.hasPermi('gas:extSale:list')")
    @GetMapping("/listUnfinish")
    public AjaxResult listUnfinish()
    {
        ExtSaleRecord extSaleRecord = new ExtSaleRecord();
        extSaleRecord.setSaleState(0);
        Map<String,Object> map = new HashMap<>();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY,0);
        calendar.set(Calendar.MINUTE,0);
        calendar.set(Calendar.SECOND,0);
        SimpleDateFormat myFmt=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        map.put("beginTime", myFmt.format(calendar.getTime()));
        map.put("endTime", myFmt.format(DateUtils.getNowDate()));
        extSaleRecord.setParams(map);
        List<ExtSaleRecord> list = extSaleRecordService.selectExtSaleRecordList(extSaleRecord);
        return AjaxResult.success(list);
    }

}
